package linc.fun.openai.config.redis;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import linc.fun.openai.handler.codec.FastJsonCodec;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;

/**
 * @author yqlin
 * @date 2022/8/27 18:52
 * @description
 */
@Slf4j
@Configuration
public class RedissonConfig {
    @Resource
    private RedisProperties redisProperties;

    @Bean
    public Redisson getRedisson() {
        Config config = new Config();
        RedisProperties.Cluster cluster = redisProperties.getCluster();

        // 配置Cluster
        if (Objects.nonNull(cluster)) {
            List<String> nodes = cluster.getNodes();
            if (CollectionUtil.isNotEmpty(nodes)) {
                ClusterServersConfig clusterServersConfig = config.useClusterServers()
                        .addNodeAddress(nodes.stream().map(node -> "redis://" + node).toArray(String[]::new));
                if (StrUtil.isNotBlank(redisProperties.getPassword())) {
                    clusterServersConfig.setPassword(redisProperties.getPassword());
                }
            }
        }
        // 没有配置Cluster
        else {
            String address = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort();
            SingleServerConfig serverConfig = config.useSingleServer();
            serverConfig.setAddress(address);
            if (!StrUtil.isEmpty(redisProperties.getPassword())) {
                serverConfig.setPassword(redisProperties.getPassword());
            }
            serverConfig.setDatabase(redisProperties.getDatabase());
        }

        // 锁续命，默认30s，这里配置成15s
        config.setLockWatchdogTimeout(15000);

        // 配置序列化
        config.setCodec(FastJsonCodec.INSTANCE);

        RedissonClient redissonClient = Redisson.create(config);

        // 配置失效监听-发布订阅模式
        // 实现 Redisson包下的 MessageListener
        /*
        RTopic topic = redissonClient.getTopic("__keyevent@0__:expired", StringCodec.INSTANCE);

        // 入群验证码校验事件
        topic.addListener(String.class, partyGroupAuthCodeEvent);
        */

        return (Redisson) redissonClient;
    }
}
